package com.sphere.freereader;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.sphere.freereader.adapter.FreeReaderAdapter;
import com.sphere.freereader.entity.BookItem;
import com.sphere.freereader.parser.HtmlParser;
import com.sphere.freereader.utils.Helper;
import com.sphere.freereader.utils.NetWorkUtils;

import java.util.List;
import java.util.Map;

/**
 * Created by aquarius on 2016/9/4.
 */
public class BookListFragment extends BaseFragment{

    private View rootView;
    private TextView mLoadingTv;
    private TextView mErrorInfoTv;
    private RecyclerView mRecyclerView;

    private Map<String, String> mCategory;
    private StringRequest mStringRequest;
    private boolean mResponseSucceed;   // 是否响应成功
    private int mRetryCount;            // 重试次数
    private String mCategoryTitle;
    private int mCurrentPosition;
    private boolean mLoadImmediately;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.book_list_fragment_layout, container, false);
        return rootView;
    }

    @Override
    protected void initialViews() {
        mLoadingTv = (TextView) rootView.findViewById(R.id.loading_tv);
        mLoadingTv.setVisibility(View.VISIBLE);
        mErrorInfoTv = (TextView) rootView.findViewById(R.id.error_info);
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        // 设置布局管理器
        mRecyclerView.setLayoutManager(new GridLayoutManager(mContext, 3));
        // 设置item增加和删除的动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());


    }

    @Override
    protected void initialDatas() {
        mResponseSucceed = false;
        mRetryCount = 0;
        mCategory = Helper.getBookCategories(mContext);
        initQueryRequest();
        // TODO: 这里尝试volley是否能拿到返回的状态，如果返回 304 Not modified 且本地有缓存的html字符串就不再用网络资源
        if(mLoadImmediately) {
            mRequestQueue.add(mStringRequest);
        }
    }

    @Override
    protected void handleOtherMessage(Message msg) {
        // 这里暂定-100的消息代表重新请求
        if (msg.what == MSG_HANDLE_OTHER) {
            reRequestBookListHtmlText();
        }
    }

    @Override
    protected void handleThreadMessage(Message msg) {
        if(msg.what == MSG_SAVE_CURRENT_BOOKLIST && msg.obj != null) {
            //List<BookItem> bookList = (List<BookItem>) msg.obj;
            //String cacheStr = Helper.getBookListStr(bookList);
            //PreferencesUtils.putString(mContext, Constants.BOOK_CATEGORY_KEY+"_"+mCurrentPosition, msg.obj.toString());
            // TODO: 分条写入数据库 category fragment对应类别的书籍列表
        }
    }

    private void reRequestBookListHtmlText(){
        if(mRequestQueue != null) {
            mRetryCount++;
            mRequestQueue.add(mStringRequest);
        }
    }

    @Override
    protected void getDataFromArguments(Bundle data) {
        mCategoryTitle = data.getString("category");
        mCurrentPosition = data.getInt("position");
        mLoadImmediately = mCurrentPosition == 0;
    }

    @Override
    protected int setCategoryType() {
        return 0;
    }

    public boolean getLoadImmediately() {
        return mLoadImmediately;
    }

    public void setLoadImmediately(boolean loadNow){
        this.mLoadImmediately = loadNow;
    }

    public void loadDataNow(boolean loadNow) {
        if(mLoadImmediately && loadNow && mStringRequest != null) {
            mRequestQueue.add(mStringRequest);
        }
    }

    public static class SimpleBookItem{
        public Bitmap bitmap;
        public String bookname;
        public String bookUrl;
    }

    private void initQueryRequest() {
        mStringRequest = new StringRequest(
                Request.Method.GET,
                mCategory.get(mCategoryTitle),
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        // 这个回调是在主线程中执行的 所以在这里设置adapter是没问题
                        android.util.Log.d("response success", "thread id =" + Thread.currentThread().getId() + ","
                                + Thread.currentThread().getName());
                        mResponseSucceed = true;
                        List<BookItem> bookList = HtmlParser.getBookList(mCategoryTitle, response);
                        mRecyclerView.setAdapter(new FreeReaderAdapter(mContext, bookList, mImageLoader));
                        mLoadingTv.setVisibility(View.GONE);
                        mHandler.obtainMessage(MSG_SAVE_CURRENT_BOOKLIST, response).sendToTarget();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // 请求时有可能返回  java.net.SocketException: recvfrom failed: ECONNRESET 导致onResponse无法执行
                        // stackoverflow上说可能是长连接的问题建议把长连接关掉
                        // Try put urlConnection.setRequestProperty("connection", "close"); before connecting.
                        // This will disable keep-alive property which is on by default
                        // 这里可能是网络的问题 所以我们采用重试机制
                        Log.d("response error", error.toString());
                        mResponseSucceed = false;
                        boolean connected = NetWorkUtils.isConnected(mContext);

                        if(connected == false /* && 数据库中没有 */) {
                            // 从数据库中读取当前categories对应的书籍列表数据 填充为List<BookItem>
                        }

                        if (connected && !mResponseSucceed && mRetryCount < 5) {
                            mHandler.sendEmptyMessage(MSG_HANDLE_OTHER);
                        }
                    }
                }
        );
    }
}
